<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="200">

            <u-form-item label="标题" prop="title" required>
                <u-input v-model="validateForm.value.title" placeholder="请输入标题"/>
            </u-form-item>

            <u-form-item label="内容" label-position="top" prop="content" required>
                <div>
                    <div>
                        <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="20" :show-progress="false" :file-list="sysFileList"
                                  @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
                    </div>
                    <div>
                        请编辑内容后保存成图片上传。
                    </div>
                </div>
            </u-form-item>

            <u-form-item label="状态" prop="status" required>
                <u-input type="select" :select-open="validateForm.controls.status.isShow" v-model="validateForm.controls.status.textDesc"
                         placeholder="请选择状态" @click="validateForm.controls.status.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>

            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.status.isShow"
                  v-model="validateForm.controls.status.isShow" :list="validateForm.controls.status.options"
                  :default-value="validateForm.controls.status.defaultValue"
                  @cancel="validateForm.controls.status.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.status)"></u-select>

    </view>
</template>

<script>
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {SysDictionaryService} from "@/dev/services/sys-dictionary.service";
    import {TbFaqService} from "@/dev/services/tb-faq.service";
    import {QiniuCloudUtil} from "@/dev/core/utils/qiniu-cloud.util";
    import {SysFileService} from "@/dev/services/sys-file.service";

    export default {
        data() {
            return {
                fileList: [],
                sysFileList: [],  // 已存在数据库的
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        communityId: this.globalVariable.userInfo.tbCommunity.id,
                        title: '',
                        content: '',
                        status: '1',
                        displayOrder: '',
                    },
                    rules: {
                        title: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                        ],
                        content: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;
            UFormUtil.setDefaultValues(this.validateForm, this.objParams);
            new SysDictionaryService().optionList('status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.status, result);
                _self.$forceUpdate();
            });
            this.findSysFileList();
        },
        methods: {
            findSysFileList() {
                const _self = this;
                new SysFileService().findSysFileList({
                    fkId: _self.validateForm.value.id,
                    type: "image/jpeg",
                    typeMark: "content",
                }).then(result => {
                    result.forEach(item => {
                        _self.sysFileList.push({
                            id: item.id,
                            url: item.content + "?_timestamp=" + new Date().getTime(),
                            isImage: true
                        });
                        _self.fileList = [..._self.sysFileList];
                        _self.validateForm.value.content = '内容已存在';
                        _self.$forceUpdate();
                    });
                });
            },
            onRemove(index) {
                console.log(index);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.fileList[index].id
                }).then(result => {
                    _self.fileList.splice(index, 1);
                    CommonUtil.toast("图片删除成功");
                    if (_self.fileList.length) {
                        _self.validateForm.value.content = '内容已存在';
                    } else {
                        _self.validateForm.value.content = '';
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'content');
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[$event.length - 1].file.path, {
                    clearOldImage: false,
                    typeMark: "content"
                }).then(result => {
                    if (result.status === "success") {
                        _self.fileList.push(result);
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }

                    if (_self.fileList.length) {
                        _self.validateForm.value.content = '内容已存在';
                    } else {
                        _self.validateForm.value.content = '';
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'content');
                    _self.$forceUpdate()
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        if (!_self.fileList.length) {
                            CommonUtil.alert("请添加内容");
                            return;
                        }
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbFaqService().updateTbFaq(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('更新成功');
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
